import React, { useState } from 'react';
import { useAsyncState, asCallApi, useApi, usePromise, callApi } from 'hooklib/async';
import s from './common.less';
import { ShowAs, AsyncState } from './common';

// 在这里可以配置 devproxy 网址，方便灵活选择后台接入点
// setPortalPathGetter(() => 'http://10.39.48.71:8083'); // 已经在 app.ts 中统一设置了

export default function CallApiExample() {

  // 全自动集成 API，自动触发，结果自动回写
  const asMenuList = useApi([],
    () => ['get /catalog/menu', {
      appCode: 'portal',
    }], {
      ForceReExecuteDelay: 1000,
      LoadingDelay: 200,
    });

  // 还可以对自动跟踪的 async state 继续跟踪手工执行的异步操作
  const onCallCatalogMenu = () => {
    asCallApi(asMenuList, 'get /catalog/menu', {
      appCode: 'portal',
    }).then(ts1a => {
      console.log(1);
      console.dir(ts1a);
    }).catch(ts1e => {
      console.error(ts1e);
    });
  }

  // 跟踪当前选中菜单
  const [selectedMenu, setSelectedMenu] = useState({} as any);
  // 跟踪子菜单加载，用于手工跟踪异步请求
  const asSubMenu = useAsyncState(`get asSubMenu ${selectedMenu.menuName}`);
  // 加载指定子菜单
  const loadSubMenu = (menuItem: any) => () => {
    setSelectedMenu(menuItem);
    asCallApi(asSubMenu, `get /${menuItem.menuUrl}`, {
      appCode: 'portal',
    });
  }

  // 主菜单清单
  const showMenuList = () => (
    <ul>
      {asMenuList.d.map((item: any) => (
        <li key={item.menuId} onClick={loadSubMenu(item)}>{item.menuName}</li>
      ))}
    </ul>
  );

  // 展示子菜单下面 catalog 清单
  const showSubMenu = () => (
    <ul>
      {asSubMenu.d.map((item: any) => (
        <li key={item.catalogId}>{item.catalogName}</li>
      ))}
    </ul>
  );

  return (
    <div>
      <button onClick={onCallCatalogMenu}>onCallCatalogMenu</button>
      <button onClick={asMenuList.re}>re-execute get menu</button>
      <div className={s.grid}>
        <ShowAs as={asMenuList} />
        <AsyncState as={asMenuList} loading={`loading menus`} fn={showMenuList} />
        <AsyncState as={asSubMenu} loading={`loading ${selectedMenu.menuName}`} fn={showSubMenu} />
      </div>
    </div>
  )
}
